
const db = wx.cloud.database()
Page({
  data: {

  },
  GetAvatar(e) {
    this.setData({
      avatarUrl: e.detail.avatarUrl
    })
  },
  GetNickname(e) {
    const userdata = wx.getStorageSync('UserData');
    if (e.detail.value === '') {
      this.setData({
        nickName: userdata.nickname
      })
    } else {
      this.setData({
        nickName: e.detail.value
      })
    }
  },
  Preserve(e) {
    const userdata = wx.getStorageSync('UserData');
    if (this.data.nickName == '' || this.data.nickName == null) {
      wx.showToast({
        title: '昵称不符合规范',
        icon: 'error'
      })
    } else {
      wx.showLoading({
        title: '信息修改中...',
        mask: true
      })

      wx.getStorage({
        key: 'UserData',
        success: res => {
          console.log(res)
          let data = res.data || {}
          data.nickname = this.data.nickName;
          data.avatar = this.data.avatarUrl;
          wx.setStorage({
            key: 'UserData',
            data: data
          })
        }
      })

      db.collection('user').where({
        _openid: userdata._openid
      }).get().then(res => {
        db.collection('user').doc(res.data[0]._id).update({
          data: {
            nickname: this.data.nickName,
            avatar: this.data.avatarUrl
          }
        }).then(res => {
          console.log(res)
        }).catch(err => {
          console.error(err)
        })
      }).catch(err => {
        console.error(err)
      })

      wx.hideLoading()
      wx.showToast({
        title: '信息修改成功',
        icon: 'success'
      })
      // wx.switchTab({
      //   url: '/pages/my/my',
      // })
    }

  },
  onLoad() {
    wx.showLoading({
      title: '数据正在加载中...',
    })
    const userdata = wx.getStorageSync('UserData');
    this.setData({
      nickName: userdata.nickname,
      avatarUrl: userdata.avatar
    })
    wx.hideLoading()
  },
  onShow() {

  }
})